package cn.cors;

import cn.hutool.core.util.StrUtil;
import cn.utils.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class CorsConfig {

    private static final String origin = "Access-Control-Allow-Origin";
    private static final String methods = "Access-Control-Allow-Methods";
    private static final String maxAge = "Access-Control-Max-Age";
    private static final String headers = "Access-Control-Allow-Headers";

    private final Cors cors;

    public CorsConfig(Cors cors) {
        this.cors = cors;
    }


    /**
     * CORS 配置
     *
     * @param httpServletResponse HTTP Servlet 响应
     * @return {@link HttpServletResponse }
     **/
    public HttpServletResponse setHttpCors(HttpServletResponse httpServletResponse) {
        httpServletResponse.setHeader(origin, cors.getAllowOrigin());
        httpServletResponse.setHeader(methods, cors.getAllowMethods());
        httpServletResponse.setHeader(maxAge, cors.getMaxAge());
        httpServletResponse.setHeader(headers, cors.getAllowHeaders());
        httpServletResponse.setCharacterEncoding(cors.getCharacterEncoding());
        return httpServletResponse;
    }

    /**
     * CORS 配置 ，
     * 方法简介:如果StrUtil.isBlank(cors.getIncludeUrl())=true就全局添加，否则过滤添加
     *
     * @param httpServletRequest  HTTP Servlet 请求
     * @param httpServletResponse HTTP Servlet 响应
     * @return {@link HttpServletResponse }
     **/
    public HttpServletResponse setHttpCors(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        String requestURL = httpServletRequest.getServletPath();
        List<String> includeUrl = Arrays.stream(cors.getIncludeUrl().split(cors.getJoin())).collect(Collectors.toList());
        //如果匹配成功添加cors
        if (StringUtils.matches(includeUrl, requestURL)) {
            return setHttpCors(httpServletResponse);
        }
        if (StrUtil.isBlank(cors.getIncludeUrl())) {
            return setHttpCors(httpServletResponse);
        }
        return httpServletResponse;
    }


}

